package com.yanggeng.demo.beginnerguidedemo.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.yanggeng.demo.beginnerguidedemo.utils.DeviceParams;
import com.yanggeng.demo.beginnerguidedemo.adapter.PhotoPreviewAdapter;
import com.yanggeng.demo.beginnerguidedemo.R;
import com.yanggeng.demo.beginnerguidedemo.utils.SnackbarUtil;
import com.yanggeng.demo.beginnerguidedemo.widget.ScaleImageView;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.AlbumLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by yanggeng on 2017/6/29.
 */

public class PhotoPreviewActivity extends BaseActivity implements PhotoPreviewAdapter.OnItemClickListener {

    private RecyclerView rlPhotos;

    private static final int REQUEST_CODE_ALBUM = 100;
    private static final int REQUEST_CODE_CAMERA = 101;
    private static final int REQUEST_CODE_GALLERY = 102;
    private GridLayoutManager layoutManager;
    private ArrayList<AlbumFile> albumFileArrayList = new ArrayList<>();
    private ArrayList<String> photos;
    private PhotoPreviewAdapter adapter;
    private Activity activity;
    private View mainView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photos);
        setTitle(true, "上传图片", "完成");
        rlPhotos = (RecyclerView) findViewById(R.id.rl_photos);
        mainView = findViewById(R.id.photo_view);
        activity = this;
        photos = new ArrayList<>();
        photos.add("+");
        Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.decoration_white, null);
        int itemSize = (DeviceParams.screenWidth(this) - (drawable.getIntrinsicWidth() * 4)) / 3;
        adapter = new PhotoPreviewAdapter(this, photos, itemSize);
        layoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        rlPhotos.setLayoutManager(layoutManager);
        rlPhotos.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        Album.initialize(AlbumConfig.newBuilder(this)
                .setAlbumLoader(new AlbumLoader() {
                    @Override
                    public void load(ImageView imageView, AlbumFile albumFile) {
                        load(imageView, albumFile.getPath());
                    }

                    @Override
                    public void load(ImageView imageView, String url) {
                        Glide.with(imageView.getContext())
                                .load(url)
                                .into(imageView);
                    }
                }).build());
    }

    @Override
    protected void navigationOnclick(int paramId) {
        if (paramId == RIGHT_TEXT) {
            postPhoto();
        }
    }

    private void postPhoto() {
        SnackbarUtil.shortSnackbar(mainView, "正在上传。。。");
        ArrayList<String> temp = new ArrayList<>();
        temp.addAll(photos);
        if (photos.size() > 0 && photos.get(photos.size() - 1).equals("+")) {
            temp.remove(photos.size() - 1);
        }
        for (int i = 0; i < temp.size(); i++) {
            File file = new File(temp.get(i));
            OkHttpUtils.post()
                    .addFile("file", file.getName(), file)
                    .url("http://i.chinalife.com.cn/imove/carservice/api/mycar/userInfo/ImgFileUpload/")
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e("--返回异常--", e.getMessage());

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            SnackbarUtil.shortSnackbar(mainView, "上传完成。。。");
                            Log.e("--返回--", response);

                        }
                    });
        }
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (photos.get(position).equals("+")) {
            Album.image(activity)
                    .multipleChoice()
                    .camera(true)
                    .selectCount(9)
                    .checkedList(albumFileArrayList)
                    .onResult(new Action<ArrayList<AlbumFile>>() {
                        @Override
                        public void onAction(@NonNull ArrayList<AlbumFile> result) {
                            Log.e("PhotoPreviewActivity", result.toString());
                            photos.clear();
                            photos.add("+");
                            albumFileArrayList.clear();
                            albumFileArrayList.addAll(result);
                            for (AlbumFile albumFile : result) {
                                photos.add(albumFile.getPath());
                            }
                            adapter.notifyDataSetChanged();
                        }
                    })
                    .start();
        } else {
//            ArrayList<String> temp = new ArrayList<String>();
//            temp.addAll(photos);
////            if(photos.size() > 0 && photos.get(photos.size() - 1).equals("+")) {
////                temp.remove(temp.size() - 1);
////            }
//            temp.remove(0);
//            Album.gallery(activity)
//                    .checkedList(temp)
//                    .currentPosition(position)
//                    .start();

            List<File> files = new ArrayList<>();
            for (AlbumFile albumFile : albumFileArrayList) {
                files.add(new File(albumFile.getThumbPath()));
            }
            ScaleImageView scaleImageView = new ScaleImageView(this);
            scaleImageView.setFiles(files, position - 1);
            scaleImageView.create();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ALBUM && resultCode == RESULT_OK) {
//            ArrayList<String> pathList = Album.parseResult(data);
//            photos.clear();
//            if(pathList.size() < 9) {
//                pathList.add("+");
//            }
//            photos.addAll(pathList);
//            adapter.setData(pathList);
        }

        if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK) {
//            ArrayList<String> pathList = Album.parseResult(data);
//            photos.clear();
//            if(pathList.size() < 9) {
//                pathList.add("+");
//            }
//            photos.addAll(pathList);
//            adapter.setData(pathList);
        }
    }
}
